<script setup>
import {reactive, ref, watch} from "vue";
import Play from "@/components/svg/Play.vue";
import {ElMessage} from "element-plus";
import VoiceWave from "@/components/svg/VoiceWave.vue";
import { onMounted, nextTick } from 'vue';

const props = defineProps({
  myUser: {
    type: reactive,
    required: true,
    default: reactive({})
  },
  currentChat: {
    type: reactive,
    required: true,
    default: reactive({})
  },
  msgHis: {
    type: ref,
    required: true,
    default: ref([])
  },
  width: {
    type: String,
    required: false,
    default: '100%'
  },
});

const srcList = ref([]);
const index = ref(0);
const playingStates = ref({});
const durations = ref({});  // 新增一个响应式对象来存储时长



// 添加新的函数来加载音频时长
// 修改加载音频时长的函数
function loadAudioDuration(msg) {
  const audio = document.getElementById(msg.id);
  if (audio) {
    audio.load();
    audio.addEventListener('loadeddata', () => {
      const duration = Math.round(audio.duration);
      if (duration && duration !== Infinity) {
        durations.value[msg.id] = duration;
      }
    });
  }
}

// 修改 onMounted 钩子
onMounted(() => {
  nextTick(() => {
    props.msgHis.forEach(msg => {
      if (msg.type === 54 || msg.type === 4) {
        loadAudioDuration(msg);
      }
    });
  });
});

// 修改 watch
watch(props.msgHis, (newMsgs) => {
  // 清理旧的 srcList
  srcList.value = [];
  // 更新图片列表
  newMsgs.forEach(msg => {
    if (msg.src) {
      srcList.value.push(msg.src);
    }
    // 同时处理新的语音消息
    if ((msg.type === 54 || msg.type === 4) && !durations.value[msg.id]) {
      loadAudioDuration(msg);
    }
  });
});

// 修改 startAudio 函数，在播放时也更新时长
function startAudio(id, msg) {
  const audio = document.getElementById(id);
  if (audio !== null) {
    // 更新时长
    if (isFinite(audio.duration)) {
      durations.value[id] = Math.round(audio.duration);
    }
    
    if (audio.paused) {
      audio.play();
      playingStates.value[id] = true;
      ElMessage('播放中...');
      
      audio.onended = () => {
        playingStates.value[id] = false;
      };
    } else {
      audio.pause();
      playingStates.value[id] = false;
      ElMessage('已暂停');
    }
  }
}
function open(url) {
  window.open(url);
}



for (let i in props.msgHis) {
  srcList.value.push(props.msgHis[i].src);
}

watch(props.msgHis, ()=>{
  for (let i in props.msgHis) {
    srcList.value.push(props.msgHis[i].src);
  }
});

// 生成随机时长的函数
function getRandomDuration() {
  return Math.floor(Math.random() * 9) + 1;  // 1-10秒的随机数
}

// 修改模板中的显示部分
</script>

<template>
  <div class="msgBox" v-for="(msg, msgHisIndex) in msgHis" :style="{'width': width}">
    <div class="msg tmsg" v-if="!msg.my">
      <img class="avatar" :src="currentChat.avatarUrl">
      <div class="text" v-if="msg.type===51">{{msg.content}}</div>
      <!--语音-->
      <div class="audio" 
           v-else-if="msg.type===54" 
           @click="startAudio(msg.id, msg)"
           :class="{ 'playing': playingStates[msg.id] }">
         <audio :id="msg.id">
           <source type="audio/mpeg" :src="msg.src">
         </audio>
         <VoiceWave class="voice-icon" />
         <span>{{getRandomDuration()}}"</span>
      </div>
      <img v-else-if="msg.type===55" class="msgImg"
                 :src="msg.src"
                 :zoom-rate="1.2"
                 :max-scale="7"
                 :min-scale="0.2"
                 :preview-src-list="srcList"
                 show-progress
                 :initial-index="index"
                 fit="cover"
      >
      <div class="share" v-else-if="msg.type===201" @click="open(msg.url)">
        <img :src="msg.coverUrl">
        <div>{{msg.title}}</div>
      </div>
    </div>
    <div class="msg mmsg" v-else>
      <img class="avatar" :src="myUser.avatarUrl">
      <div class="text" v-if="msg.type===1">{{msg.content}}</div>
      <!--语音-->
      <div class="audio" 
           v-else-if="msg.type===4" WW
           @click="startAudio(msg.id, msg)"
           :class="{ 'playing': playingStates[msg.id] }">
         <audio :id="msg.id">
           <source type="audio/mpeg" :src="msg.src">
         </audio>
         <VoiceWave class="voice-icon" />
         <span>{{getRandomDuration()}}"</span>
      </div>
      <img v-else-if="msg.type===5" class="msgImg"
                ref="imageRef"
                :src="msg.src"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="srcList"
                show-progress
                :initial-index="index"
                fit="cover"
      >
    </div>
  </div>
</template>
<style scoped>
.msgBox {
  min-height: 40px;
  color: black;
  height: auto;
  overflow: hidden;
}
.msgBox .msg {
  line-height: 33px;
  margin-top: 7px;
}
.msgBox .msg .avatar {
  width: 33px;
  height: 33px;
  border-radius: 20px;
  user-select: none;
}
.msgBox .msg .text {
  border-radius: 5px;
  padding: 0 10px;
}
.msgBox .msg .audio {
  border-radius: 10px;
  padding: 0 13px;  /* 修改padding，移除顶部padding */
  width: 120px;
  height: 34px;
  cursor: pointer;
  display: flex;
  align-items: center;  /* 垂直居中 */
  justify-content: flex-start;  /* 水平方向靠左对齐 */
  transition: all 0.3s ease;
}

.msgBox .msg .audio span {
  font-size: 14px;
  line-height: 1;  /* 确保文字不会影响整体高度 */
}

.msgBox .msg .audio svg {
  margin-right: 10px;
  flex-shrink: 0;  /* 防止svg图标被压缩 */
}

.msgBox .msg .audio:hover {
  opacity: 0.8;
  transform: scale(1.02);
}

.msgBox .msg .audio .voice-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
}

/* 修改动画效果 */
@keyframes playing {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}

.audio.playing .voice-icon {
  animation: playing 1.2s ease-in-out infinite;
}

/* 为接收方和发送方的语音图标设置不同的颜色 */
.tmsg .audio .voice-icon {
  color: #666;
}

.mmsg .audio .voice-icon {
  color: #2e3238;
}
.msgBox .msg .audio {
  border-radius: 10px;
  padding: 0 13px;
  width: auto;  /* 改为自适应宽度 */
  min-width: 80px;  /* 设置最小宽度 */
  height: 34px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  transition: all 0.3s ease;
}

.msgBox .msg .audio span {
  font-size: 14px;
  line-height: 1;
  color: #999;  /* 设置时长文字颜色 */
  margin: 0 5px;  /* 添加左右间距 */
  white-space: nowrap;  /* 防止文字换行 */
}

.msgBox .msg .audio svg {
  margin-right: 10px;
  flex-shrink: 0;  /* 防止svg图标被压缩 */
}

.msgBox .msg .audio:hover {
  opacity: 0.8;
  transform: scale(1.02);
}

.msgBox .msg .audio svg {
  margin-right: 10px;
}

/* 添加播放动画 */
@keyframes playing {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.audio.playing svg {
  animation: playing 1s infinite;
}
.msgBox .msg .msgImg {
  max-width: 400px !important;
  border-radius: 5px;
  margin-right: 5px;
  box-shadow: 0 0 1px 0 rgba(10,10,10,1);
}
.msgBox .msg .share {
  width: 250px;
  box-shadow: 0 0 1px 0 rgba(10,10,10,1);
  height: 190px;
}
.msgBox .msg .share img {
  width: 100%;
  vertical-align: bottom;
  height: 170px;
}
.msgBox .msg .share div {
  width: 100%;
  height: 20px;
  line-height: 20px;
}


.msgBox .tmsg {
  float: left;
}
.tmsg .avatar {
  float: left;
  margin-left: 7px;
}
.tmsg .text {
  float: left;
  margin-left: 7px;
  background-color: rgb(255,255,255);
}
.tmsg .audio {
  float: left;
  margin-left: 7px;
  background-color: rgb(255,255,255);
}
.tmsg .msgImg {
  max-width: 400px !important;
  border-radius: 5px;
  margin-left: 7px;
  float: left;
}
.tmsg .share {
  float: left;
  margin-left: 7px;
}
.tmsg .share img {
  width: 100%;
}
.tmsg .share div {
  width: 100%;
}


.msgBox .mmsg {
  float: right;
}
.mmsg .avatar {
  float: right;
  margin-right: 7px;
}
.mmsg .text {
  float: right;
  margin-right: 7px;
  background-color: #95EC69;
}
.mmsg .audio {
  float: right;
  margin-right: 7px;
  background-color: #95EC69;
}
.mmsg .msgImg {
  float: right;
  max-width: 400px !important;
  border-radius: 5px;
  margin-right: 7px;
}
.mmsg .share {
  float: right;
  margin-right: 7px;
}
.mmsg .share img {
  width: 100%;
}
.mmsg .share div {
  width: 100%;
}

</style>

@keyframes wave1 {
  0%, 100% { transform: scaleY(1); }
  50% { transform: scaleY(0.4); }
}

@keyframes wave2 {
  0%, 100% { transform: scaleY(0.4); }
  50% { transform: scaleY(1); }
}

.audio.playing .voice-icon g rect:nth-child(1) {
  animation: wave1 0.8s infinite;
  transform-origin: bottom;
}

.audio.playing .voice-icon g rect:nth-child(2) {
  animation: wave2 0.8s infinite;
  animation-delay: 0.2s;
  transform-origin: bottom;
}

.audio.playing .voice-icon g rect:nth-child(3) {
  animation: wave1 0.8s infinite;
  animation-delay: 0.4s;
  transform-origin: bottom;
}

.msgBox .msg .audio .voice-icon {
  width: 18px;
  height: 18px;
}
